package com.yxcz.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.yxcz.model.UpdateUserInfoForm;
import com.yxcz.model.User;
import com.yxcz.service.LoginService;
import com.yxcz.service.UserService;
import com.yxcz.util.ImageHelper;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private LoginService loginService;
	@Resource
	private UserService userService;

	/**
	 * 登陆页面控制
	 * 
	 * @return
	 */
	@RequestMapping("/login")
	public String loginPage() {
		return "User/loginPage";
	}

	/**
	 * 提交登陆表单
	 * 
	 * @param user
	 * @param modelAndView
	 * @param session
	 * @return
	 */
	@RequestMapping("/doLogin")
	public ModelAndView doLogin(User user, ModelAndView modelAndView, HttpSession session) {

		try {
			loginService.login(user);
			session.setAttribute("accountName", user.getAccountName());
			/* CheckLoginInterceptor.getMenu().put(user.getAccountName(), ); */
			modelAndView.setViewName("redirect:/Admin/index");
			return modelAndView;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			modelAndView.addObject("accountName", user.getAccountName());
			modelAndView.addObject("errorMsg", "登录失败,请检查用户名或密码是否正确或帐号是否启用!");
			modelAndView.setViewName("User/loginPage");
			return modelAndView;
		}
	}

	@RequestMapping("/json_test")
	@ResponseBody
	public HashMap<String,String> json_test() {
		
	      HashMap<String,String> map=new HashMap<>();
	      map.put("一号", "张三");
	      map.put("二号", "李三");

		return map;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param form
	 * @param bindingResult
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping("/updateUserInfo")
	public ModelAndView updateUserInfo(@Validated UpdateUserInfoForm form, BindingResult bindingResult,
			ModelAndView modelAndView) {

		if (bindingResult.hasErrors())
			modelAndView.setViewName("redirect:/Common/500Page");
		else {
			userService.updateUserInfo(form);
			modelAndView.addObject("msg", "修改");
			modelAndView.setViewName("Common/success");
		}

		return modelAndView;

	}

	/**
	 * 上传用户图片
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("/uploadUserPhoto")
	@ResponseBody
	public String uploadUserPhoto(MultipartFile file, HttpServletRequest request) {

		String path = request.getSession().getServletContext().getRealPath("/resources/Upload/UserPhoto");
		if (file == null)
			return null;
		String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
				file.getOriginalFilename().length());

		if (!(type.equals(".jpg") || type.equals(".png") || type.equals(".jpeg")))
			return null;

		String fileName = new Date().getTime() + request.getSession().getAttribute("accountName").toString() + type;
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		// 保存
		try {
			file.transferTo(targetFile);

		} catch (Exception e) {
			return null;
		}
   System.out.println(path);
		return "/resources/Upload/UserPhoto/" + fileName;
	}

	/**
	 * 更新用户头像
	 * 
	 * @param photourl
	 * @param request
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping("/updatePhoto")
	public ModelAndView updateUserInfo(String photourl, HttpServletRequest request, ModelAndView modelAndView, int x,
			int y, int w, int h) {
		modelAndView.addObject("msg", "修改");
		if (photourl == null || photourl == "") {
			modelAndView.setViewName("redirect:/Common/500Page");
			return modelAndView;
		}

		String path = request.getSession().getServletContext().getRealPath("") + photourl;
		try {
			String type = photourl.substring(photourl.lastIndexOf(".") + 1, photourl.length());
			ImageHelper.cutImage(path, path, x, y, w, h, type);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		userService.updateUserPhoto(
				loginService.getUserInfo(request.getSession().getAttribute("accountName").toString()).getId(),
				photourl);
		modelAndView.setViewName("Common/success");
		return modelAndView;

	}

	/**
	 * 用户信息展示
	 * 
	 * @return
	 */
	@RequestMapping("/profile")
	public String profile() {
		return "User/profile";
	}

	/**
	 * 登出
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/signout")
	public String signout(HttpSession session) {
		session.removeAttribute("accountName");
		return "redirect:/user/login";
	}

	@RequestMapping(value = "/tool")
	public ModelAndView tool(ModelAndView modelAndView) {
		String path = "E://有毒.bbb";
		File file = new File(path);
		Scanner sc;
		String content = "";

		try {
			sc = new Scanner(file);
			while (sc.hasNext()) {
				content += sc.next();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		modelAndView.addObject("content", content);
		modelAndView.setViewName("User/tool");
		return modelAndView;

	}



	@RequestMapping(value = "/changePassword")
	public ModelAndView changePassword(ModelAndView modelAndView) {

		modelAndView.setViewName("User/changePassword");

		return modelAndView;

	}

	@RequestMapping(value = "/doChangePassword")
	public ModelAndView doChangePassword(String password, String repassword,HttpSession session,ModelAndView modelAndView) {

		if (password == null || password == "" || !password.equals(repassword) ) {
			modelAndView.setViewName("redirect:/Common/500Page");
			return modelAndView;
		}
		
		userService.updatePassword(loginService.getUserInfo(session.getAttribute("accountName").toString()),password);

		modelAndView.setViewName("Common/success");
		return modelAndView;

	}
	
	


}
